//
//  VideoPreloader.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/8.
//

import Foundation
import AVFoundation

// MARK: - 视频控制视图
protocol VideoControlViewDelegate: AnyObject {
    func didChangePlaybackRate(_ rate: Float)
    func didSeekTo(_ progress: Float)
    func didTogglePlayPause()
}

// MARK: - 视频预加载器
class VideoPreloader {
    static let shared = VideoPreloader()
    private var cache: [URL: AVAsset] = [:]
    private let preloadQueue = DispatchQueue(label: "com.videopreloader.queue", qos: .userInitiated)
    private let maxCacheCount = 5
    
    // 根据网络状况调整的预加载策略
    var preferredBitrate: Double {
        switch NetworkMonitor.shared.currentNetworkType {
        case .wifi: return 5_000_000 // 5 Mbps
        case .cellular: return 1_500_000 // 1.5 Mbps
        case .unknown: return 1_000_000 // 1 Mbps
        }
    }
    
    private init() {}
    
    func preloadVideos(_ videos: [VideoItem]) {
        let preloadCount = calculatePreloadCount()
        for video in videos.prefix(preloadCount) {
            preloadVideo(video)
        }
    }
    
    func preloadVideo(_ video: VideoItem) {
        let url = video.videoUrl
        
        // 如果已经在缓存中，则跳过
        if cache[url] != nil || VideoCacheManager.shared.isCached(url: url) { return }
        
        preloadQueue.async { [weak self] in
            let asset = AVURLAsset(url: url)
            let playerItem = AVPlayerItem(asset: asset)
            // 设置自适应码率
            if #available(iOS 11.0, *) {
//                asset.loadValuesAsynchronously(forKeys: ["preferredPeakBitRate"]) {
//                    asset.preferredPeakBitRate = self?.preferredBitrate ?? 1_500_000
//                }
                playerItem.preferredPeakBitRate = self?.preferredBitrate ?? 1_500_000
            }
            
            // 异步加载关键属性
            asset.loadValuesAsynchronously(forKeys: ["duration", "tracks"]) {
                // 检查加载状态
                var error: NSError?
                let durationStatus = asset.statusOfValue(forKey: "duration", error: &error)
                let tracksStatus = asset.statusOfValue(forKey: "tracks", error: &error)
                
                if durationStatus == .loaded && tracksStatus == .loaded {
                    // 添加到缓存
                    DispatchQueue.main.async {
                        self?.addToCache(url: url, asset: asset)
                    }
                    
                    // 启动后台缓存
                    VideoCacheManager.shared.cacheVideo(from: url)
                }
            }
        }
    }
    
    func calculatePreloadIndices(currentIndex: Int, totalCount: Int, networkType: NetworkType) -> [Int] {
        var indices: [Int] = []
        
        switch networkType {
        case .wifi:
            // WiFi下预加载3个视频
            for i in 1...3 {
                let index = currentIndex + i
                if index < totalCount {
                    indices.append(index)
                }
            }
        case .cellular:
            // 移动网络下预加载1个视频
            let index = currentIndex + 1
            if index < totalCount {
                indices.append(index)
            }
        case .unknown:
            // 未知网络不预加载
            break
        }
        
        return indices
    }
    
    private func calculatePreloadCount() -> Int {
        switch NetworkMonitor.shared.currentNetworkType {
        case .wifi: return 3
        case .cellular: return 1
        case .unknown: return 0
        }
    }
    
    func cachedAsset(for url: URL) -> AVAsset? {
        return cache[url]
    }
    
    private func addToCache(url: URL, asset: AVAsset) {
        cache[url] = asset
        
        // 限制缓存大小
        if cache.count > maxCacheCount {
            // 简单策略：移除最旧的缓存项
            if let firstKey = cache.keys.first {
                cache.removeValue(forKey: firstKey)
            }
        }
    }
    
    func clearCache() {
        cache.removeAll()
    }
}
